<template :style="dataTable">
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item label="项目时间">
					<el-date-picker v-model="params.time" type="month" placeholder="选择时间"></el-date-picker>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="serBtn()">查询</el-button>
				</el-form-item>
				<!--@click="excelWay()"-->
				<el-form-item>
					<el-button type="primary" ><a :href="excelUrl" :download="excelFileName" style="color: #fff"> 导出</a></el-button>
				</el-form-item>
			</el-form>
		</el-col>
		<el-table :height=heightData :data="dataList" style="width: 100%">
			<el-table-column type="expand">
				<template slot-scope="props">
					<el-form label-position="left" inline class="demo-table-expand">
						<el-form-item label="">
							<div class="row table-info-list" v-for="d in props.row.details">
								<span class="times"><label></label> <p class="time">{{d.time}}</p></span>
								<span class="names"><label></label> <p>{{d.name}}</p></span>
							</div>
						</el-form-item>

					</el-form>
				</template>
			</el-table-column>

			<el-table-column label="人员名称"	prop="name"></el-table-column>
			<el-table-column label="工时" prop="count">
				<template slot-scope="scope">
				<el-tag :type="scope.row.tag === '0' ? 'primary' : ''"	disable-transitions>{{scope.row.count}} 时</el-tag></template>
			</el-table-column>
		</el-table>

	</section>
</template>

<script>
    import util from '../../common/js/util'
    import insurance from '../../api/insurance';
    import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

    export default {
        data() {
            return {
                params: {
                    id:31,
                    time:'2016-08',
                    page: 1,     //  当前页
                    pageSize: 10,    //  每页行数
                },
				excelUrl:'',	// 导出excel 路径
                excelFileName:'',// 导出excel 文件名称
				proList:[],
				proTableStr:'',
				tableDatas:[],
                loginID:0,
                dataSum:0,
                userId:0,
                userList:[],
                totalRecord:0,  //  总记录数
                filters:{'name':''},
                dataList:[],
                total: 0,
                page: 1,
                listLoading: false,
                sels: [],//列表选中列

                heightData: document.body.clientHeight-260,
                dataTable:document.body.clientHeight-260,
            }
        },
        methods: {
            formatter(row, column) {
                return row.count+' 时';
            },
            filterTag(value, row) {
                console.log(value)
                return row.tag === value+' 时';
            },
            // 查询
            serBtn(){
                this.getProList();     // 调用公共列表方法
            },
            //  每页行数 选择事件
            handleSizeChange(val) {
                this.params.pageSize = val;        // 分页参数 每页行数 （赋值全局变量）
                this.getProList();  // 调用公共列表方法
            },

            // 当前页数 点击事件
            handleCurrentChange(val) {
                this.params.page  = val;    // 分页参数 当前页数 （赋值全局变量）
                this.getProList();     // 调用公共列表方法
            },
            //获取项目列表
            getProList() {
                this.listLoading = true;
                var that = this;
                var d = new Date(that.params.time);
                $.ajax(insurance.posturl+"count/time/all?year="+d.getFullYear()+"&month="+parseInt(d.getMonth()+1),{
                    headers: {'Content-Type': 'application/json;charset=UTF-8'},
                    'type': 'GET',
                    success:function (res) {
                        res = JSON.parse(JSON.parse(res).Content);
                        // that.totalRecord = res.count;
                        for(var i = 0; i< res.length; i++){
                            if(JSON.stringify(res[i].details).length > 2) {
                                var arr = JSON.stringify(res[i].details).replace(/({|}|"|")/g, '').split(',');
                                var data = [];
                                arr.forEach(function (item,index,input){
									var d = item.split(':');
                                    var ds = {'name':d[0].replace(/("|")/g, ''),'time':d[1].replace(/("|")/g, '')+' 时'};
                                    data.push(ds);
                                });
                               res[i].details = data;
                            }
                        }
						that.dataList = res;
                        console.log(that.dataList)
                        that.listLoading = false;
                    }
                });
                that.excelWay();
            },
            // 获取用户列表
            getUser(){
                var that = this;
                $.ajax(insurance.posturl+"user/AllUsers?page=0&pageSize=200",{
                    headers: {'Content-Type': 'application/json;charset=UTF-8'},
                    'type': 'GET',
                    success:function (res) {
                        res = JSON.parse(JSON.parse(res).Content);
                        var data = [];
                        for(var i = 0; i<res.list.length; i++){
                            data.push({'value':res.list[i].id,'label':res.list[i].name})
                        }
                        that.userList = data;
                        var data3 = [];
                        for(var i = 0; i<res.list.length; i++){
                            data3.push({'key':res.list[i].id,'label':res.list[i].name});
                        }
                        window.localStorage.setItem('userList2', JSON.stringify(data3));
                    }
                });
            },
            //获取项目列表
            getProListAll() {
                var that = this;
               	that.proTableStr = '<tr><td colspan = "4"  style =“text-align：center;”>154</td>';
                that.proList = [];
                $.ajax(insurance.posturl+"proj/allProjs?page=0&pageSize=1000&usrID=99&mode=3&name=",{
                    headers: {'Content-Type': 'application/json;charset=UTF-8'},
                    'type': 'GET',
                    success:function (res) {
                        res = JSON.parse(JSON.parse(res).Content);
                        for(var i = 0; i<res.list.length; i++){
                            if(res.list[i].status !== 2){
                                that.proTableStr+=`<td colspan = "4"  style =“text-align：center;”>${ res.list[i].projectName + '\t'}</td>`;
                                that.proList.push({'name':res.list[i].projectName,'ID':res.list[i].ID});
                            }
                        }
                        that.proTableStr +='</tr>';
                    }
                });
            },
			excelWay(){
                //列标题
                // 标题循环
                var str = this.proTableStr;
                str += '<tr><td>序号</td><td>姓名</td><td>工时</td><td>调休工时</td>';
                for(var i = 0; i<this.proList.length; i++){
                    str += '<td>统计工时</td><td>工期（30%）</td><td>质量（30%）</td><td>考核工时</td>';
				}
                str += '</tr>';
                //循环遍历，每行加入tr标签，每个单元格加td标签

				// 数据循环
                for(let i = 0 ; i < this.dataList.length ; i++ ){
                    str+='<tr>';
                    str+=`<td>${ i + '\t'}</td>`;
                    for(let item in this.dataList[i]){
                        //增加\t为了不让表格显示科学计数法或者其他格式
                        var d = this.dataList[i][item];
                        if(item === 'details'){
                            var dd = '';
                            for(var k = 0; k<this.dataList[i][item].length; k++){
                                dd = '时间'+this.dataList[i][item][k].time+'名称'+this.dataList[i][item][k].name+' // ';
                            }
                            // str+=`<td>${ dd + '\t'}</td>`;
                        }else{
                            str+=`<td>${ d + '\t'}</td>`;
                        }
                    }
                    str+=`<td>${ '0' + '\t'}</td>`;
                    // console.log(this.dataList[i]);
                    for(var j = 0; j<this.proList.length; j++){
                        str+=`<td>${ this.dataList[i].count + '\t'}</td><td>${ '' + '\t'}</td><td>${ '' + '\t'}</td><td>${ '' + '\t'}</td>`;
                    }

                    str += '</str>';
                }
                this.tableDatas = str;
                //Worksheet名
                var worksheet = 'Sheet1';
                var uri = 'data:application/vnd.ms-excel;base64,';
                //下载的表格模板数据
                var template = `<html xmlns:o="urn:schemas-microsoft-com:office:office"+
      xmlns:x="urn:schemas-microsoft-com:office:excel"
      xmlns="http://www.w3.org/TR/REC-html40">
      <meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">
      <meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">
      <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
        <x:Name>${worksheet}</x:Name>
        <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
        </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
        </head><body><table>${str}</table></body></html>`;
                this.excelUrl = uri + this.base64(template);
				var dates = new Date();
                var month = parseInt(dates.getMonth())+1;
				this.excelFileName = dates.getFullYear() +'.' +month+ '.' +dates.getDate() +'员工工时统计'
                // window.location.href = uri + this.base64(template)

			},
            base64(s){
                return window.btoa(unescape(encodeURIComponent(s)))
            },
        },
        mounted() {
            this.getProListAll();
            this.loginID = JSON.parse(sessionStorage.getItem('user')).id;
            if(JSON.parse(sessionStorage.getItem('user')).id != 99){
                this.params.id = JSON.parse(sessionStorage.getItem('user')).id;
            }
            var t = new Date;
            this.params.time = t.getFullYear() +'-'+ parseInt(t.getMonth()+1);
            this.getUser();
            this.getProList();
        }
    }
</script>

<style scoped>
.table-info-list{float: left;width: 100%; overflow: hidden; display: block; padding: 0px;}
.table-info-list span{overflow: hidden; margin-right: 20px; float:left;}
.table-info-list label,.table-info-list p{float: left; margin-left: 6px;}
.table-info-list label{color: #999;}
.table-info-list p{color: #666;}
.table-info-list .times{min-width: 100px;}
.table-info-list .times .time{text-align: right; width: 96%;}
</style>